﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using TSB.SharePointUrlShortener.DAL;

namespace TSB.SharePointUrlShortener.Layouts.TSB.SharePointUrlShortener
{
    public partial class Short_Urls : LayoutsPageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Context.Request.QueryString["delete"] != null)
            {
                DeleteShortCode(Context.Request.QueryString["delete"]);
            }

            if (!IsPostBack)
            {
                GenerateDefaultShortcode();
            }

            btnCreate.Click += btnCreate_Click;

            BindAllShortUrls();
        }

        void btnCreate_Click(object sender, EventArgs e)
        {
            var shortCode = txtShortcode.Text;
            var url = txtUrl.Text;

            if (string.IsNullOrEmpty(shortCode) || string.IsNullOrEmpty(url))
            {
                ltErrors.Text = "Missing Short Code or Url";
                return;
            }

            var urlShortenerRepository = new UrlShortenerRepository();
            if (urlShortenerRepository.CreateShortener(shortCode, url))
            {
                ltErrors.Text = "Yeap";
            }
            else
            {
                ltErrors.Text = "Problem Short Url";
            }
        }

        void BindAllShortUrls()
        {
            var urlShortenerRepository = new UrlShortenerRepository();
            rptShortUrls.DataSource = urlShortenerRepository.GetAllShortcodes();
            rptShortUrls.ItemDataBound += rptShortUrls_ItemDataBound;
            rptShortUrls.DataBind();
        }

        void rptShortUrls_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem)
            {
                return;
            }

            var ltShortCode = e.Item.FindControl("ltShortCode") as Literal;
            var ltUrl = e.Item.FindControl("ltUrl") as Literal;
            var lnkGo = e.Item.FindControl("lnkGo") as HyperLink;
            var lnkDelete = e.Item.FindControl("lnkDelete") as HyperLink;
            var dt = e.Item.DataItem is KeyValuePair<string, string> ? (KeyValuePair<string, string>) e.Item.DataItem : new KeyValuePair<string, string>();

            if (ltShortCode == null || ltUrl == null || lnkGo == null || lnkDelete == null)
            {
                return;
            }

            ltShortCode.Text = dt.Key;
            ltUrl.Text = dt.Value;
            lnkGo.NavigateUrl = string.Format("{0}/url/{1}", SPContext.Current.Site.RootWeb.Url, dt.Key);
            lnkGo.Target = "_blank";
            lnkDelete.NavigateUrl = string.Format("{0}?delete={1}", Context.Request.Path, dt.Key);
        }

        void DeleteShortCode(string shortCode)
        {
            var urlShortenerRepository = new UrlShortenerRepository();
            if (urlShortenerRepository.DeleteByShortcode(shortCode))
            {
                Context.Response.Redirect(Context.Request.Path);
            }
            else
            {
                ltErrors.Text = string.Format("There was a problem deleting the short url '{0}'", shortCode);
            }
        }

        void GenerateDefaultShortcode()
        {
            var urlShortenerRepository = new UrlShortenerRepository();
            txtShortcode.Text = urlShortenerRepository.GenerateShortCode();
        }
    }
}
